import axios from 'axios';

import { ElMessage } from 'element-plus'

import appConfig from '@/config';

import { useUserStore } from '@/store/modules/user';

// 创建 axios 实例
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 10000,
    headers: { "Content-Type": "application/json;charset=utf-8" },
});


// 请求拦截器
service.interceptors.request.use(
    (config) => {
        const userStore = useUserStore();
        const { accessToken } = userStore;
        if (accessToken) {
            config.headers.Authorization = accessToken;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        // 检查配置的响应类型是否为二进制类型（'blob' 或 'arraybuffer'）, 如果是，直接返回响应对象
        if (response.config.responseType === "blob" ||
            response.config.responseType === "arraybuffer") {
            return response;
        }
        const { code, data, msg } = response.data;
        if (code === appConfig.SUCCESS) {
            return data;
        }

        ElMessage.error(msg || "系统出错");
        return Promise.reject(new Error(msg || "Error"));
    },
    (error) => {
        // 异常处理
        if (error.response.data) {
        const { code, msg } = error.response.data;
        if (code === appConfig.tokenInvalid) {
            ElNotification({
            title: "提示",
            message: "您的会话已过期，请重新登录",
            type: "info",
            });
            useUserStoreHook()
            .resetToken()
            .then(() => {
                location.reload();
            });
        } else {
            ElMessage.error(msg || "系统出错");
        }
        }
        return Promise.reject(error.message);
    }
);
export default service;